package com.kinon.market.view;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.kinon.market.Constatus;
import com.kinon.market.R;
import com.kinon.market.data.DataModel;
import com.kinon.market.data.UPacketFactory;
import com.kinon.market.fragment.DingdanFragment;
import com.kinon.market.fragment.OrderFragment;
import com.kinon.market.fragment.PandianFragment;
import com.kinon.market.fragment.QucanFragment;
import com.kinon.market.fragment.RukuFragment;
import com.kinon.market.fragment.RukudingdanFragment;
import com.kinon.market.fragment.ShezhiFragment;
import com.kinon.market.fragment.ShouyinFragment;
import com.kinon.market.tools.MyFragmentReplace;
import com.kinon.market.tools.SharedPreferencesUtil;

import java.io.File;

import sunmi.ds.DSKernel;
import sunmi.ds.callback.ICheckFileCallback;
import sunmi.ds.callback.IConnectionCallback;
import sunmi.ds.callback.ISendCallback;
import sunmi.ds.data.DataPacket;

public class MainActivity extends FragmentActivity {
    /**
     * 副屏相关参数
     */
    private static final String SHOW_IMG_LIST_ID = "SHOW_IMG_LIST_ID";
    private static final String WELCOME_IMG_ID = "WELCOME_IMG_ID";
    private final static String SHOW_VIDEO_LIST_DATA_ID = "SHOW_VIDEO_LIST_DATA_ID";
    private final static String SHOW_IMGS_LIST_DATA_ID = "SHOW_IMGS_LIST_DATA_ID";
    public static Activity context;
    long taskId;
    String pathBig = Environment.getExternalStorageDirectory().getPath() + "/dcim/caizhengting.png";
    DSKernel mDSKernel;// SDK核心类
    DataPacket dsPacket;
    IConnectionCallback mConnCallback = new IConnectionCallback() {// SDK链接状态回调
        @Override
        public void onDisConnect() {
        }

        @Override
        public void onConnected(final ConnState state) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//					Toast.makeText(MainActivity.this, "state:"+state, Toast.LENGTH_LONG).show();
                    switch (state) {
                        case AIDL_CONN:
                            //与本地service的连接畅通
                            break;
                        case VICE_SERVICE_CONN:
                            //与副屏service连接畅通
                            long fileId = SharedPreferencesUtil.getLong(MainActivity.this, SHOW_IMG_LIST_ID);
                            long fileId1 = SharedPreferencesUtil.getLong(MainActivity.this, WELCOME_IMG_ID);
                            long fileId2 = SharedPreferencesUtil.getLong(MainActivity.this, SHOW_VIDEO_LIST_DATA_ID);
                            long fileId3 = SharedPreferencesUtil.getLong(MainActivity.this, SHOW_IMGS_LIST_DATA_ID);
                            if (fileId2 != -1L) {
                                checkImg(fileId2, SHOW_VIDEO_LIST_DATA_ID);
                            }
                            if (fileId3 != -1L) {
                                checkImg(fileId3, SHOW_IMGS_LIST_DATA_ID);
                            }
                            if (fileId != -1L) {
                                checkImg(fileId, SHOW_IMG_LIST_ID);
                            }
                            if (fileId1 != -1L) {
                                checkImg(fileId1, WELCOME_IMG_ID);
                            }
                            break;
                        case VICE_APP_CONN:
                            //与副屏app连接畅通
                            break;

                        default:
                            break;
                    }

                }
            });
        }
    };
    /**
     * 收银
     */
    private RadioButton rb_shouyin;
    private RadioButton rb_qucan;
    private RadioButton rb_order;
    /**
     * 入库
     */
    private RadioButton rb_ruku;
    /**
     * 入库单
     */
    private RadioButton rb_rukudan;
    /**
     * 订单
     */
    private RadioButton rb_dingdan;
    /**
     * 盘点
     */
    private RadioButton rb_pandian;
    /**
     * 设置
     */
    private RadioButton rb_shezhi;
    private TextView tv_hint;
    private int IS_CURRENT_PAGE = 1;
    //自定义广播
    private UrgentBroadcastReceiver broadcast = new UrgentBroadcastReceiver();
    private OnClickListener rbOnClickListener = new OnClickListener() {
        @SuppressWarnings("deprecation")
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                // 收银
                case R.id.rb_shouyin:
                    if (IS_CURRENT_PAGE != 1) {
                        ShouyinFragment shouyin = new ShouyinFragment();
                        MyFragmentReplace.fragmentReplace(MainActivity.this,
                                R.id.fram_fanqiedingcan, shouyin);
//					rb_shouyin.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
//					rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_ruku.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_rukudan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_pandian.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
                        IS_CURRENT_PAGE = 1;
//					startActivityForResult(intent, requestCode)
                    }
                    break;
                // 入库
                case R.id.rb_ruku:
                    if (IS_CURRENT_PAGE != 2) {
                        RukuFragment ruku = new RukuFragment();
                        MyFragmentReplace.fragmentReplace(MainActivity.this,
                                R.id.fram_fanqiedingcan, ruku);
//					rb_ruku.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
//					rb_shouyin.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_rukudan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_pandian.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
                        IS_CURRENT_PAGE = 2;

                    }
                    break;
                // 订单
                case R.id.rb_dingdan:
                    if (IS_CURRENT_PAGE != 3) {
                        DingdanFragment dingdan = new DingdanFragment();
                        MyFragmentReplace.fragmentReplace(MainActivity.this,
                                R.id.fram_fanqiedingcan, dingdan);
//					rb_dingdan.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
//					rb_shouyin.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_ruku.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_rukudan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_pandian.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
                        IS_CURRENT_PAGE = 3;
                    }
                    break;
                // 盘点
                case R.id.rb_pandian:
                    if (IS_CURRENT_PAGE != 4) {
                        PandianFragment pandian = new PandianFragment();
                        MyFragmentReplace.fragmentReplace(MainActivity.this,
                                R.id.fram_fanqiedingcan, pandian);
//					rb_pandian.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
//					rb_shouyin.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_ruku.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_rukudan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
                        IS_CURRENT_PAGE = 4;
                    }
                    break;

                // 设置
                case R.id.rb_shezhi:
                    if (IS_CURRENT_PAGE != 5) {
                        ShezhiFragment shezhi = new ShezhiFragment();
                        MyFragmentReplace.fragmentReplace(MainActivity.this,
                                R.id.fram_fanqiedingcan, shezhi);
//					rb_shezhi.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
//					rb_shouyin.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_ruku.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_rukudan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_pandian.setBackgroundColor(getResources().getColor(R.color.white));
                        IS_CURRENT_PAGE = 5;
                    }
                    break;
                // 入库单
                case R.id.rb_rukudan:
                    if (IS_CURRENT_PAGE != 6) {
                        RukudingdanFragment rukudan = new RukudingdanFragment();
                        MyFragmentReplace.fragmentReplace(MainActivity.this,
                                R.id.fram_fanqiedingcan, rukudan);
//						rb_rukudan.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
//						rb_shouyin.setBackgroundColor(getResources().getColor(R.color.white));
//						rb_ruku.setBackgroundColor(getResources().getColor(R.color.white));
//						rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
//						rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
//						rb_pandian.setBackgroundColor(getResources().getColor(R.color.white));
                        IS_CURRENT_PAGE = 6;
                    }
                    break;
                case R.id.rb_qucan:
                    if (IS_CURRENT_PAGE != 7) {
                        QucanFragment qucan = new QucanFragment();
                        MyFragmentReplace.fragmentReplace(MainActivity.this,
                                R.id.fram_fanqiedingcan, qucan);
                        IS_CURRENT_PAGE = 7;
                    }
                    break;

                case R.id.rb_order:
                    if (IS_CURRENT_PAGE != 8) {
                        OrderFragment order = new OrderFragment();
                        MyFragmentReplace.fragmentReplace(MainActivity.this,
                                R.id.fram_fanqiedingcan, order);
                        IS_CURRENT_PAGE = 8;
                    }
                    break;

                default:
                    break;
            }

        }
    };
    /**
     * 双击返回键退出
     */
    private long exitTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        initRes();
        initSDK();
        registerBroadcast();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (outState != null) {
            outState.remove("android:support:fragments");
        }

    }

    /**
     * 注册广播方法
     */
    private void registerBroadcast() {
        //表名接收广播类型
        IntentFilter filter =
                new IntentFilter(UrgentSetActivity.LOGIN_ACTION);
        LocalBroadcastManager.getInstance(getApplicationContext())
                .registerReceiver(broadcast, filter);
    }

    /**
     * 销毁广播，避免内存泄漏
     */
    private void unregisterBroadcast() {
        LocalBroadcastManager.getInstance(getApplicationContext())
                .unregisterReceiver(broadcast);
    }

    @Override
    protected void onStart() {
        super.onStart();
        showWelcomeImage();
    }

    /**
     * 副屏初始化设置
     */
    private void initSDK() {
        mDSKernel = DSKernel.newInstance();
        mDSKernel.init(this, mConnCallback);
        showWelcomeImage();
    }

    private void checkImg(long fileId, final String key) {

        mDSKernel.checkFileExist(fileId, new ICheckFileCallback() {
            @Override
            public void onCheckFail() {
            }

            @Override
            public void onResult(boolean b) {
                if (!b) {
                    SharedPreferencesUtil.put(MainActivity.this, key, -1L);
                } else {
                }
            }
        });
    }

    @SuppressWarnings("deprecation")
    private void initRes() {
//		fram_jishibao = (FrameLayout) findViewById(R.id.fram_jishibao);
        rb_shouyin = (RadioButton) findViewById(R.id.rb_shouyin);
        rb_ruku = (RadioButton) findViewById(R.id.rb_ruku);
        rb_rukudan = (RadioButton) findViewById(R.id.rb_rukudan);
        rb_dingdan = (RadioButton) findViewById(R.id.rb_dingdan);
        rb_pandian = (RadioButton) findViewById(R.id.rb_pandian);
        rb_shezhi = (RadioButton) findViewById(R.id.rb_shezhi);
        rb_qucan = (RadioButton) findViewById(R.id.rb_qucan);
        rb_order = (RadioButton) findViewById(R.id.rb_order);
        tv_hint = (TextView) findViewById(R.id.tv_hint);

        //判断是否是紧急模式
        if (Constatus.URGENT_TYPE) {
            tv_hint.setVisibility(View.VISIBLE);
        }
//		classintent();

        ShouyinFragment shouyin = new ShouyinFragment();
        MyFragmentReplace.fragmentReplace(MainActivity.this,
                R.id.fram_fanqiedingcan, shouyin);
//			rb_shouyin.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
//			rb_ruku.setBackgroundColor(getResources().getColor(R.color.white));
//		    rb_rukudan.setBackgroundColor(getResources().getColor(R.color.white));
//			rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
//			rb_pandian.setBackgroundColor(getResources().getColor(R.color.white));
//			rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
//		}
        setRbOnClick();
    }

    private void setRbOnClick() {
        rb_shouyin.setOnClickListener(rbOnClickListener);
        rb_ruku.setOnClickListener(rbOnClickListener);
        rb_rukudan.setOnClickListener(rbOnClickListener);
        rb_dingdan.setOnClickListener(rbOnClickListener);
        rb_pandian.setOnClickListener(rbOnClickListener);
        rb_shezhi.setOnClickListener(rbOnClickListener);
        rb_qucan.setOnClickListener(rbOnClickListener);
        rb_order.setOnClickListener(rbOnClickListener);
    }

    /**
     * 隐藏上下状态栏
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 副屏加载图片
     */
    private void showWelcomeImage() {
        taskId = SharedPreferencesUtil.getLong(this, WELCOME_IMG_ID);
        if (taskId != -1L) {
            showImgWelcome(taskId);
            return;
        }

        File file = new File(pathBig);
        if (!file.exists()) {
            Toast.makeText(getApplicationContext(), "No file!", Toast.LENGTH_SHORT).show();
            return;
        }
        taskId = mDSKernel.sendFile(DSKernel.getDSDPackageName(), pathBig, new ISendCallback() {
            @Override
            public void onSendSuccess(long l) {
                showImgWelcome(taskId);
                SharedPreferencesUtil.put(getApplicationContext(), WELCOME_IMG_ID, taskId);
            }

            @Override
            public void onSendFail(int i, String s) {
            }

            @Override
            public void onSendProcess(long l, long l1) {
            }
        });
    }

    private void showImgWelcome(long taskId) {
        String json1 = UPacketFactory.createJson(DataModel.SHOW_IMG_WELCOME, "");
        mDSKernel.sendCMD(DSKernel.getDSDPackageName(), json1, taskId, null);
    }

    private class UrgentBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (!Constatus.URGENT_TYPE) {
                tv_hint.setVisibility(View.GONE);
            } else {
                tv_hint.setVisibility(View.VISIBLE);
            }
        }
    }

}
